<?php

namespace app\modules\admin\controllers;

use app\core\YpBaseController;
use app\extensions\XUtils;
use app\libs\STD3Des;
use app\models\Admin;
use app\services\AdminService;
use app\services\CommonService;
use Yii;
use app\libs\XCaptcha;

/**
 * 后台登录控制器
 * @author chenym
 * @since 2017.7.5
 * Public controller for the `admin` module
 */
class PublicController extends YpBaseController
{
    //默认是登录action
    public $defaultAction = 'login';
    public $layout        = "admin";
    public $bodyClass     = '';

    public function init()
    {
        parent::init();
    }

    public function beforeAction($action)
    {
        //$this->enableCsrfValidation = true;//前端自定义表单时，要关闭csrf验证用fasle，否则会找不到显示400 Bad Request
        return parent::beforeAction($action); // TODO: Change the autogenerated stub
    }

    /**
     * 登录
     */
    public function actionLogin()
    {
        $adminModel   = new Admin();
        $adminModel->setScenario('login');
        $adminService = new AdminService();
        if (Yii::$app->request->isPost) {

            $adminPostArray         = Yii::$app->request->post('Admin');
            $adminModel->attributes = $adminPostArray;
            if ($adminModel->validate()) {

                //模型中已初步验证用户的基本数据,现在这里判断是否锁定、是否超过3个月未登录
                $user = $adminModel::find()
                                ->asArray()
                                ->where(['userName' => $adminPostArray['username']])
                                ->one();

                if ($user['isLock'] == 1) {
                    $adminModel->addError('username', '登录错误次数过多，用户已经锁定，请联系管理！');
                } elseif ($user['lastLoginTime'] && (time() - $user['lastLoginTime'] > 86400 * 30 * 3)) {
                    $adminService->updateUserGroupForbiddenByUserId($user['id']);
                    $adminModel->addError('username', '超过3个月未登录，用户已经被锁定，请联系管理！');
                } else {
                    $adminService->login($user);
                    $adminService->insertTraceLog("用户登录成功", $user['id'], $user['userName']);
                    $url = Yii::$app->urlManager->createUrl('admin/default/index');
                    $this->redirect($url);
                }
            } else {
                $adminModel->errors;
            }
            
        }
        $assign = [
            'model' => $adminModel,
        ];
        return $this->render('login', $assign);
    }
    public function actionUpdate()
    {
        $userId = 395;
        $admin = new Admin();
        //$udada = Admin::findOne($userId);
        $udada = Admin::findByPk($userId);
        var_dump($udada);
        $udada->groupId = 2;
        //$res = $udada->save(false);
        $res = $udada->save();
        var_dump($res);


    }
    /**
     * 退出登录
     */
    public function actionLogout()
    {
        $adminService = new AdminService();
        $adminService->insertTraceLog("用户登退出成功", $adminService::getLoginUserIdFromSession(), $adminService::getLoginUserNameFromSession(), "logout");
        $adminService::removeUserLoginSession();
        $this->redirect(['public/login']);

    }

    /**
     * 验证码显示
     */
    public function actionCode()
    {
        $acaptcha = new XCaptcha();
        $acaptcha->entryCode();
        exit;
    }

    /**
     * 忘记密码
     */
    public function actionForget()
    {
        $commonService = new CommonService();
        $adminService  = new AdminService();
        if (Yii::$app->request->isPost) {

            $adminPostArray = Yii::$app->request->post('Admin');

            $xCaptcha = new XCaptcha();
            $verifyRes      = $xCaptcha->checkCode($adminPostArray['verifyCode']);
            if (!$verifyRes) {
                XUtils::message('error', "验证码错误！");
            }

            $userName       = $adminPostArray['username'];
            $email          = $adminPostArray['email'];
            if (empty($userName) || empty($email)) {
                XUtils::message('error', "请填写完整信息！");
            }
            $conditions = [
                "userName" => $userName,
                "email"    => $email
            ];
            $userInfo   = $adminService->checkUserByCondition($conditions);
            if (empty($userInfo)) {
                XUtils::message("error", "这个邮箱还没有被注册", '/admin/public/forget');
            } else {
                $id      = $userInfo['id'];
                $str     = base64_encode($id . "^#" . time() . "^#" . $email);
                $key     = Yii::$app->params['keyConfig']['key'];
                $iv      = Yii::$app->params['keyConfig']['iv'];
                $des     = new STD3Des(base64_encode($key), base64_encode($iv));
                $str     = urlencode($des->encrypt($str));
                $mailTo  = $email;
                $subject = "要出发官网后台密码重置"; //邮件主题
                $body    = "<h1> 复制此链接修改密码 </h1>" . $_SERVER['HTTP_HOST'] . "/admin/public/reset?setpwd=" . $str; //邮件内容
                $sent    = $commonService->sendmailto($mailTo, $subject, $body, false);
                if ($sent) {
                    XUtils::message('success', '修改密码的链接已发送到你的邮箱', '/admin/public/forget');
                } else {
                    XUtils::message('error', '修改密码的链接发送到邮箱时失败，请确认填写邮箱是否正确', '/admin/public/forget');
                }
            }
        }
        return $this->render('forget');
    }

    /**
     * 重置密码
     */
    public function actionReset()
    {
        $adminModel    = new Admin();
        $adminService  = new AdminService();
        $commonService = new CommonService();
        $setpwd        = Yii::$app->request->get("setpwd");
        $pwdStr        = $setpwd;
        if (empty($setpwd)) {
            XUtils::message("error", "缺少服务器传递参数，请点击邮箱重置链接！");
        }
        $key    = Yii::$app->params['descKey']['cookieDesc']['backenKey'];
        $iv     = Yii::$app->params['descKey']['cookieDesc']['backendIv'];
        $des    = new STD3Des(base64_encode($key), base64_encode($iv));
        $setpwd = $des->decrypt($setpwd);

        $setpwd       = base64_decode($setpwd);
        $messageArray = explode('^#', $setpwd);
        $id           = $messageArray[0];
        $time         = $messageArray[1];
        $email        = $messageArray[2];
        if (time() > $time + 30 * 60) {
            header("content-type:text/html;charset=utf8");
            echo "链接有效期已过，请重新提交申请！";
            exit;
        } else {
            $conditions = [
                "id"    => $id,
                "email" => $email
            ];
            $return     = $adminService->checkUserByCondition($conditions);
            if (empty($return)) {
                XUtils::message("error", "修改密码的链接发送到邮箱时失败，请确认填写邮箱是否正确");
            }
        }

        if (Yii::$app->request->isPost) {
            //重置密码
            $Admin        = Yii::$app->request->post('Admin');
            $newPassword  = $Admin['newpassword'];
            $newPassword2 = $Admin['newpassword2'];
            if (empty($newPassword)) {
                XUtils::message("error", '请填写新密码');
            } elseif (empty($newPassword2)) {
                XUtils::message("error", '请填写确认密码');
            } elseif ($newPassword != $newPassword2) {
                XUtils::message("error", '两次密码输入不一致');
            } elseif ($commonService->passwordValidator($newPassword) < 3) {
                XUtils::message("error", '密码不能小于6个字符或者全为数字或者全为字母,且必须包含“/[_|\-|+|=|*|!|@|#|$|%|^|&|(|)]”特殊字符');
            } else {
                $password   = $adminService->hashPassword($return['userName'], $newPassword);
                $where      = [
                    "where" => "id={$return['id']}"
                ];
                $updateData = ['password' => $password, 'updateTime' => time()];
                $result     = $adminModel->dbUpdate('', $updateData, $where);
                if ($result) {
                    XUtils::message('success', '密码重置成功', '/admin/public/login');
                } else {
                    XUtils::message("error", '密码重置失败', '/admin/public/reset?setpwd=' . $pwdStr);
                }
            }
        }
        return $this->render('reset');
    }
}
